﻿using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Util;
using Kingdee.BOS.Orm.DataEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.ServiceHelper;
using System.Data;
using System.ComponentModel;

namespace GuoXinDa.FormPlugin
{
    [Description("表单插件：采购申请明细上需显示所有物料在途还有多少数量"), HotUpdate]
    public class SetTransitQty : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            string formId = this.Model.BillBusinessInfo.GetForm().Id;
            if (formId.EqualsIgnoreCase("PUR_Requisition"))
            {
                var obj = this.Model.DataObject;
                DynamicObject ApplicationOrg = obj["ApplicationOrgId"] as DynamicObject;
                long ApplicationOrgId = ApplicationOrg == null ? 0 : Convert.ToInt64(ApplicationOrg["Id"]);
                DynamicObjectCollection rows = obj["ReqEntry"] as DynamicObjectCollection;
                if (rows != null && rows.Count > 0)
                {
                    for (int i = 0; i < rows.Count; i++)
                    {
                        DynamicObject material = rows[i]["MaterialId"] as DynamicObject;
                        long materialId = material == null ? 0 : Convert.ToInt64(material["Id"]);

                        //已审核采购申请单的剩余数量（未下采购订单、未调拔）
                        decimal unPurQty = GetUnPurQty(materialId, ApplicationOrgId);
                        //采购订单的未入库数量（订单数量-入库数量）
                        decimal unInQty = GetUnInQty(materialId, ApplicationOrgId);
                        //调拔申请-已直接调拔数量
                        decimal unTranQty = GetUnTranQty(materialId, ApplicationOrgId);

                        decimal unTransitQty = unPurQty + unInQty + unTranQty;
                        this.Model.SetValue("FTransitQty", unTransitQty, i);
                    }
                }
            }
        }

        private decimal GetUnTranQty(long materialId, long applicationOrgId)
        {
            decimal unTranQty = 0;
            string sqlStr = string.Format($@" /*dialect*/ 
            SELECT ISNULL(SUM(T1.FQty), 0) FQty
            FROM T_STK_STKTRANSFERAPP T0
                 JOIN T_STK_STKTRANSFERAPPENTRY T1 ON T1.FID = T0.FID
            WHERE T0.FDOCUMENTSTATUS = 'C'
                  AND T1.FMATERIALID = {materialId}
                  AND T0.FAPPORGID = {applicationOrgId};");
            DataSet dataSet = DBServiceHelper.ExecuteDataSet(this.Context, sqlStr);
            decimal appQty = Convert.ToDecimal(dataSet.Tables[0].Rows[0][0]);

            sqlStr = string.Format($@" /*dialect*/ 
            SELECT ISNULL(SUM(T0.FQty),0) FQty
            FROM T_STK_STKTRANSFERINENTRY T0
                 JOIN T_STK_STKTRANSFERINENTRY_LK T1 ON T1.FENTRYID = T0.FENTRYID
                 JOIN T_STK_STKTRANSFERAPPENTRY T2 ON T2.FID = T1.FSBILLID
                                                      AND T2.FENTRYID = T1.FSID
                 JOIN T_STK_STKTRANSFERIN T3 ON T3.FID = T0.FID
            WHERE T1.FSTABLENAME = 'T_STK_STKTRANSFERAPPENTRY'
                  AND T3.FDOCUMENTSTATUS = 'C'
                  AND T0.FMATERIALID = {materialId}
                  AND T3.FSTOCKOUTORGID = {applicationOrgId};");
            DataSet ds2 = DBServiceHelper.ExecuteDataSet(this.Context, sqlStr);
            decimal tranQty = Convert.ToDecimal(ds2.Tables[0].Rows[0][0]);
            unTranQty = appQty - tranQty;
            return unTranQty;
        }

        private decimal GetUnInQty(long materialId, long applicationOrgId)
        {
            decimal inQty = 0;
            string sqlStr = string.Format($@" /*dialect*/ 
            SELECT ISNULL(SUM(T2.FREMAINSTOCKINQTY), 0) FREMAINSTOCKINQTY
            FROM t_PUR_POOrder T0
                 JOIN t_PUR_POOrderEntry T1 ON T1.FID = T0.FID
                 JOIN T_PUR_POORDERENTRY_R T2 ON T2.FENTRYID = T1.FENTRYID
            WHERE T0.FDOCUMENTSTATUS = 'C'
                  AND T0.FCANCELSTATUS = 'A'
                  AND T1.FMATERIALID = {materialId}
                  AND T0.FPURCHASEORGID = {applicationOrgId};");
            DataSet dataSet = DBServiceHelper.ExecuteDataSet(this.Context, sqlStr);
            inQty = Convert.ToDecimal(dataSet.Tables[0].Rows[0][0]);
            return inQty;
        }

        private decimal GetUnPurQty(long materialId, long applicationOrgId)
        {
            decimal purQty = 0;
            string sqlStr = string.Format($@" /*dialect*/ 
            SELECT ISNULL(SUM(T2.FREMAINQTY), 0) FREMAINQTY
            FROM T_PUR_Requisition T0
                 JOIN T_PUR_ReqEntry T1 ON T1.FID = T0.FID
                 JOIN T_PUR_REQENTRY_R T2 ON T2.FENTRYID = T1.FENTRYID
            WHERE T0.FDOCUMENTSTATUS = 'C'
                  AND T0.FCancelStatus = 'A'
                  AND T1.FMATERIALID = {materialId}
                  AND T0.FAPPLICATIONORGID = {applicationOrgId};");
            DataSet dataSet = DBServiceHelper.ExecuteDataSet(this.Context, sqlStr);
            purQty = Convert.ToDecimal(dataSet.Tables[0].Rows[0][0]);
            return purQty;
        }
    }
}
